package stack;

import java.util.Stack;

//逆序打印单链表,有的题目不允许破坏单链表,因此不能逆转单链表
public class Test2 {
    static class Node{

        public String val;
        public Node next;

        public Node(String val) {
            this.val = val;
        }
    }

    //采用了函数递归的方法,从后往前开始打印,调到reversePrint(d)时,
    // 判断到reversePrint(head.next)结束,并打印d,逐渐向前递归,这种方法比较难以理解,用栈来解题更简单
    public static void reversePrint(Node head){
        if(head == null){
            return;
        }
//        reversePrint(head.next);
//        System.out.print(head.val + " ");
        Stack<Node> stack = new Stack<>();
        for(Node cur = head;cur != null;cur = cur.next){
            stack.push(cur);
        }
        while(!stack.isEmpty()){
            System.out.print(stack.pop().val + " ");
        }
    }

    public static Node build(){
        Node a = new Node("a");
        Node b = new Node("b");
        Node c = new Node("c");
        Node d = new Node("d");
        a.next = b;
        b.next = c;
        c.next = d;
        return a;
    }

    public static void main(String[] args) {
        Node head = build();
        reversePrint(head);
    }
}
